package com.wanpinghui.wphlibrary.model.db.manager;

import com.wanpinghui.wphlibrary.model.message.bean.MsgBean;
import com.wanpinghui.wphlibrary.model.message.bean.RecentMsgBean;
import com.wanpinghui.wphlibrary.model.oauth.UserInfoUtil;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserInformation;
import com.yunshl.yunshllibrary.storage.MDBManager;
import com.yunshl.yunshllibrary.utils.TextUtil;

import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by xiongning on 17-12-5.
 */

public class MsgDbManager {

    public static final int PAGE_SIZE=10;

    private static MsgDbManager instance;

    private MsgDbManager() {

    }

    public static MsgDbManager getInstance(){
        if(instance==null){
            instance=new MsgDbManager();
        }
        return instance;
    }

    public void saveMsbBean(MsgBean msgBean){
        try {
            MDBManager.getInstance().getDbManager().saveOrUpdate(msgBean);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void saveMsbBeanList(List<MsgBean> datas){
        try {
            MDBManager.getInstance().getDbManager().saveOrUpdate(datas);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public List<MsgBean> getMsbBeans(String imId,long create_at){
        boolean idDesc = true;//是否倒序，默认false
        List<MsgBean> datas=null;
        try {
            if (create_at > 0) {
                datas = MDBManager.getInstance().getDbManager().selector(MsgBean.class)
                        .where("account", "=", imId)
                        .and("created_at", "<", create_at)
                        .orderBy("created_at", idDesc)
                        .limit(PAGE_SIZE)
                        .offset(0)
                        .findAll();
            }else {
                datas = MDBManager.getInstance().getDbManager().selector(MsgBean.class)
                        .where("account", "=", imId)
                        .orderBy("created_at", idDesc)
                        .limit(PAGE_SIZE)
                        .offset(0)
                        .findAll();
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        /*if(datas!=null && datas.size()>0) {
            Collections.sort(datas, new Comparator<MsgBean>() {
                *//*
                * int compare(MsgBean lhs, MsgBean rhs) 返回一个基本类型的整型，
                * 返回负数表示：lhs rhs，
                * 返回0 表示：o1和o2相等，
                * 返回正数表示：o1大于o2。
                *//*
                @Override
                public int compare(MsgBean lhs, MsgBean rhs) {
                    if(lhs.getCreated_at() > rhs.getCreated_at()){
                        return 1;
                    }
                    if(lhs.getCreated_at() == rhs.getCreated_at()){
                        return 0;
                    }
                    return -1;
                }
            });
        }*/
        return datas;
    }

    public List<MsgBean> getMsbBeans(String imId,int curPage){
        boolean idDesc = true;//是否倒序，默认false
        List<MsgBean> datas=null;
        try {
            datas=MDBManager.getInstance().getDbManager().selector(MsgBean.class)
                    .where("account", "=", imId)
                    .orderBy("created_at", idDesc)
                    .limit(PAGE_SIZE)
                    .offset((curPage-1)*PAGE_SIZE)
                    .findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }
       if(datas!=null && datas.size()>0) {
            Collections.sort(datas, new Comparator<MsgBean>() {
             /*
             * int compare(MsgBean lhs, MsgBean rhs) 返回一个基本类型的整型，
             * 返回负数表示：lhs rhs，
             * 返回0 表示：o1和o2相等，
             * 返回正数表示：o1大于o2。
             */
                @Override
                public int compare(MsgBean lhs, MsgBean rhs) {
                    if(lhs.getCreated_at() > rhs.getCreated_at()){
                        return 1;
                    }
                    if(lhs.getCreated_at() == rhs.getCreated_at()){
                        return 0;
                    }
                    return -1;
                }
            });
        }
        return datas;
    }

    public String getMyImId(){
        String myImId=null;
        UserBean ub= UserInfoUtil.getUserInfo();
        if(ub!=null){
            UserInformation uinf=ub.getUser();
            if(uinf!=null){
                myImId=ub.getUser().getId();
            }
        }
        return myImId;
    }


    public void updateRecentMsgBean(RecentMsgBean msgBean){
        try {
                MDBManager.getInstance().getDbManager().saveOrUpdate(msgBean);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void updateRecentMsgBeanList(List<RecentMsgBean> datas){
        try {
            MDBManager.getInstance().getDbManager().delete(RecentMsgBean.class);
            if(datas!=null && datas.size()>0)
                MDBManager.getInstance().getDbManager().saveOrUpdate(datas);

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void saveRecentMsgBeanList(List<MsgBean> msgBeens,boolean isChating){

        if(msgBeens!=null && msgBeens.size()>0){

            for(MsgBean msg:msgBeens){

                saveRecentMsgBean(msg,isChating);
            }
        }

    }



    public void saveRecentMsgBean(MsgBean msgBean,boolean isChating){

        String groupId=msgBean.getGroupId();

        List<RecentMsgBean> datas=getRecentMsgBeans();

        RecentMsgBean history=null;

        if(datas!=null){

            for(RecentMsgBean rmb:datas){

                if(TextUtil.equals(rmb.getGroup_id(),groupId)){

                    history=rmb;

                    break;
                }
            }
        }

        RecentMsgBean nrmb=new RecentMsgBean();

        nrmb.setGroup_id(groupId);

        nrmb.setTo_id(msgBean.getTo_id());

        nrmb.setFrom_id(msgBean.getFrom_id());

        nrmb.setMessage(msgBean.getMessage());

        nrmb.setMsg_type(msgBean.getMsg_type());

        nrmb.setCreated_at(msgBean.getCreated_at());

        if(history!=null)
            nrmb.setUn_read_count(history.getUn_read_count()+(isChating?0:1));
        else
            nrmb.setUn_read_count((isChating?0:1));

        try {
            if(history!=null)
                MDBManager.getInstance().getDbManager().delete(history);
            MDBManager.getInstance().getDbManager().saveOrUpdate(nrmb);

        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    public List<RecentMsgBean> getRecentMsgBeans(){

        List<RecentMsgBean> datas=null;
        try {
            datas=MDBManager.getInstance().getDbManager().selector(RecentMsgBean.class).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }

        return datas;

    }


}
